﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using BCCommon.OAEnums;
using BCEntity.OA.ApplyOrder;
using BCCommon;

namespace BCData.OA.ApplyOrder
{
    public class ApplyOrderData : IApplyOrderData
    {
        private const string QUERY = @" SELECT ApplyOrderId,Type,`Status`,ApplyCode,DepartmentId,DepartmentName,Title,Content,AdminId,AdminName,CreateTime,ModifierId,ModifierName,ModifyTime,ApprovalAdminIds,IsRead,CopierIds,CompanyId FROM  OA_ApplyOrder ";

        private readonly IDatabaseContext databaseContext;

        public ApplyOrderData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }

        /// <summary>
        /// 分页获取申请信息列表
        /// </summary>
        /// <param name="adminId">当前登录人员</param>
        /// <param name="pageIndex">分页页码</param>
        /// <param name="pageSize">分页页数</param>
        /// <param name="ascending">是否升序排</param>
        /// <param name="type">申请类型</param>
        /// <param name="status">申请单审核状态</param>
        /// <param name="isMyApproved">是否我审批的</param>
        /// <param name="isMyCreated">由我发起的</param>
        /// <param name="isCopierToMe">抄送给我的</param>
        /// <param name="adminId">抄送给我的</param>
        /// <returns></returns>
        public async Task<(IEnumerable<ApplyOrderEntity>, int)> GetAsync(long adminId, int pageIndex, int pageSize, bool ascending, OAApplyOrderType? type, OAApplyOrderStatus? status, bool? isMyApproved, bool? isMyCreated, bool? isCopierToMe, int? companyId)
        {
            string sql = QUERY;

            DynamicParameters parameters = new DynamicParameters();
            var wheres = new List<string>();
            if (companyId.HasValue)
            {
                wheres.Add(" CompanyId=?CompanyId");
                parameters.Add("?CompanyId", companyId, DbType.Int64, size: 20);
            }
            parameters.Add("?pageIndex", (pageIndex - 1) * pageSize, DbType.Int32);
            parameters.Add("?pageSize", pageSize, DbType.Int32);
            if (type.HasValue)
            {
                wheres.Add(" Type=?Type");
                parameters.Add("?Type", type.Value.ToString(), DbType.AnsiString);
            }
            if (status.HasValue)
            {
                wheres.Add(" Status=?Status");
                parameters.Add("?Status", status.Value.ToString(), DbType.AnsiString);
            }
            if (isMyApproved.HasValue && isMyApproved.Value)
            {
                wheres.Add(" FIND_IN_SET(?AdminId,ApprovalAdminIds)");
                parameters.Add("?AdminId", adminId, DbType.Int64);
            }
            else
            {
                if (adminId > 0)
                {
                    wheres.Add(" AdminId=?AdminId");
                    parameters.Add("?AdminId", adminId, DbType.Int64);
                }
            }
            if (isMyCreated.HasValue && isMyCreated.Value)
            {
                wheres.Add(" AdminId=?AdminId");
                parameters.Add("?AdminId", adminId, DbType.Int64);
            }
            if (isCopierToMe.HasValue && isCopierToMe.Value)
            {
                wheres.Add(" FIND_IN_SET(?AdminId,CopierIds)");
                parameters.Add("?AdminId", adminId, DbType.Int64);
            }

            sql = string.Format("{0} {2} ORDER BY CreateTime {1} LIMIT ?pageIndex,?pageSize; SELECT COUNT(1) FROM OA_ApplyOrder {2} ;",
                sql,
                ascending ? "ASC" : "DESC",
                wheres.Count > 0 ? string.Format(" WHERE {0}", string.Join(" AND ", wheres)) : string.Empty);

            return await this.databaseContext.Slave.QueryMultipleAsync<ApplyOrderEntity,int>(sql, parameters);
        }

        /// <summary>
        /// 获取指定的OA申请单
        /// </summary>
        /// <param name="applyOrderId"></param>
        /// <returns></returns>
        public async Task<ApplyOrderEntity> GetById(long applyOrderId)
        {
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?ApplyOrderId", applyOrderId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<ApplyOrderEntity>(string.Format("{0} Where ApplyOrderId=?ApplyOrderId", QUERY), parameters);
        }

        /// <summary>
        /// 更新指定的申请单为已读
        /// </summary>
        /// <param name="applyOrderId"></param>
        /// <returns></returns>
        public async Task<ApplyOrderEntity> UpdateApplyOrderRead(long applyOrderId, string adminName, long adminId)
        {
            string sql = SqlCommands.GetUpdateSql("OA_ApplyOrder", new string[] { "IsRead", "ModifierName", "ModifyTime", "ModifierId" }, new string[] { "ApplyOrderId" });
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?ApplyOrderId", applyOrderId, DbType.Int64);
            parameters.Add("?IsRead", true, DbType.Boolean);
            parameters.Add("?ModifierId", adminId, DbType.Int64);
            parameters.Add("?ModifierName", adminName.Trim(), DbType.AnsiString, size: 30);
            parameters.Add("?ModifyTime", DateTime.Now, DbType.DateTime);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<ApplyOrderEntity>(string.Format("{0} {1} Where ApplyOrderId=?ApplyOrderId", sql, QUERY), parameters,databaseContext.Transaction);
        }

        /// <summary>
        /// 新增一个申请信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<ApplyOrderEntity> InsertAsync(ApplyOrderEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("OA_ApplyOrder", new string[] { "Type", "Status", "ApplyCode", "CompanyId", "DepartmentId", "DepartmentName", "Title", "Content", "AdminId", "AdminName", "ApprovalAdminIds", "IsRead", "CopierIds" });
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?Type", entity.Type, DbType.AnsiString);
            parameters.Add("?ApplyCode", entity.ApplyCode, DbType.AnsiString);
            parameters.Add("?Status", OAApplyOrderStatus.Pending.ToString(), DbType.AnsiString);
            parameters.Add("?DepartmentId", entity.DepartmentId, DbType.Int64);
            parameters.Add("?DepartmentName", entity.DepartmentName, DbType.AnsiString);
            parameters.Add("?Title", entity.Title, DbType.AnsiString);
            parameters.Add("?Content", entity.Content, DbType.AnsiString);
            parameters.Add("?CompanyId", entity.CompanyId, DbType.Int32);
            parameters.Add("?AdminId", entity.AdminId, DbType.Int64);
            parameters.Add("?AdminName", entity.AdminName, DbType.AnsiString);
            parameters.Add("?ApprovalAdminIds", entity.ApprovalAdminIds, DbType.AnsiString);
            parameters.Add("?CopierIds", entity.CopierIds, DbType.AnsiString);
            parameters.Add("?IsRead", false, DbType.Boolean);
            string querySql = string.Format("{0} {1} Where  ApplyCode=?ApplyCode ", sql, QUERY);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<ApplyOrderEntity>(querySql, parameters, databaseContext.Transaction);
        }

        /// <summary>
        /// 更新指定的申请单审批人信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<ApplyOrderEntity> UpdateApprovalAdminIdsAsync(ApplyOrderEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("OA_ApplyOrder", new string[] { "ApprovalAdminIds", }, new string[] { "ApplyCode" });
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?ApplyCode", entity.ApplyCode, DbType.AnsiString);
            parameters.Add("?ApprovalAdminIds", entity.ApprovalAdminIds, DbType.AnsiString);
            string querySql = string.Format("{0} {1} Where  ApplyCode=?ApplyCode ", sql, QUERY);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<ApplyOrderEntity>(querySql, parameters, databaseContext.Transaction);
        }

        /// <summary>
        /// 更新指定的申请单审批人信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<ApplyOrderEntity> UpdateStatusAsync(ApplyOrderEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("OA_ApplyOrder", new string[] { "ModifyTime", "ModifierId", "ModifierName", "Status", }, new string[] { "ApplyCode" });
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?ApplyCode", entity.ApplyCode, DbType.AnsiString);
            parameters.Add("?ModifierId", entity.ModifierId, DbType.Int64);
            parameters.Add("?ModifyTime", DateTime.Now, DbType.DateTime);
            parameters.Add("?Status", entity.Status.ToString(), DbType.AnsiString);
            parameters.Add("?ModifierName", entity.ModifierName, DbType.AnsiString, size: 30);
            string querySql = string.Format("{0} {1} Where  ApplyCode=?ApplyCode ", sql, QUERY);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<ApplyOrderEntity>(querySql, parameters, databaseContext.Transaction);
        }

        /// <summary>
        /// 获取指定的OA申请单
        /// </summary>
        /// <param name="applyOrderNo">根据申请单号</param>
        /// <returns></returns>
        public async Task<ApplyOrderEntity> GetByApplyOrderNoAsync(string applyOrderNo)
        {
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?ApplyCode", applyOrderNo, DbType.AnsiString, size: 50);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<ApplyOrderEntity>(string.Format("{0} Where ApplyCode=?ApplyCode", QUERY), parameters);

        }
    }
}
